using UnityEngine;
using System;
using Newtonsoft.Json.Linq;

public class VersionInfo
{
    public string packageVersion;
    public string serverUrl;  // 关键字段：服务器地址
    public string channel;
    public string subChannel;
    // 其他字段按需添加...
}
public class LoginManager : UnitySingleton<LoginManager>
{
    // 单例模式（可选）
    // public static LoginManager Instance { get; private set; }


    // 服务器配置
    private string _serverUrl = "http://192.168.8.128:8080/";
    private string _socketAddress = "192.168.8.128";
    private int _socketPort = 8080;

    // 网络组件
    private SocketClient _socketClient;

    private VersionInfo _versionInfo;
    
    public string SocketAddress = "";
    public int SocketPort;
    public int ServerId;
    public int state;
    public string sign = "d13b3e8ef74bf72d8aafce3a1c8672a0";

    public string openId;
    public string token;
    public bool isLogin;

    // private void Awake()
    // {
    //     if (Instance == null)
    //     {
    //         Instance = this;
    //         DontDestroyOnLoad(gameObject);
    //     }
    //     else
    //     {
    //         Destroy(gameObject);
    //     }
    // }
    //
    private void Start()
    {
        InitializeNetwork();
    }
    
    
    private void InitializeNetwork()
    {
        // 初始化Socket连接
        _socketClient = NetworkManager.Instance.AddSocket(SocketType.LOGIN,_socketAddress, _socketPort);
    
        // 绑定事件
        _socketClient.OnConnects += OnSocketConnected;
        _socketClient.OnConnectFails += OnSocketConnectFailed;
        _socketClient.OnDisconnect += OnSocketDisconnected;
    }

    // 提供给UI按钮调用的登录方法
    public void Login(string username, string password)
    {
        // 1.先通过HTTP验证账号
        string loginUrl = $"{_serverUrl}/api/login?user={username}&pwd={password}";
        NetworkManager.Instance.SendGetHttp(loginUrl, OnLoginResponse, OnHttpRequestFailed);
    }
    
    private void OnLoginResponse(string jsonResponse)
    {
        // 解析登录响应（示例，需根据实际API调整）
        var response = JsonUtility.FromJson<LoginResponseHttp>(jsonResponse);
    
        if (response.success)
        {
            // 保存UserID
            AppConst.UserId = response.userId;
           // AppConst.Token = response.token;
    
            // 连接游戏服务器
            _socketClient.TryConnect();
        }
        else
        {
            Debug.LogError($"登录失败: {response.errorMessage}");
            // 显示错误提示UI...
        }
    }

    // Socket连接成功回调
    private void OnSocketConnected(SocketClient client)
    {
        Debug.Log("Socket连接成功，发送登录数据...");

        // 构造登录消息包
        ByteBuffer buffer = new ByteBuffer();
        buffer.WriteIntToByte(AppConst.UserId);
        buffer.WriteIntToByte(AppConst.Token);

        // 发送登录协议（假设协议号1000是登录）
        _socketClient.SendMessage(1000, buffer);
    }

    // 其他回调方法...
    private void OnSocketConnectFailed(SocketClient client)
    {
        Debug.LogError("Socket连接失败！");
    }

    private void OnSocketDisconnected(SocketClient client)
    {
        Debug.LogWarning("Socket连接断开");
    }

    private void OnHttpRequestFailed()
    {
        Debug.LogError("HTTP请求失败");
    }

    private void OnDestroy()
    {
        if (_socketClient != null)
        {
            // _socketClient.OnConnects -= OnSocketConnected;
            // _socketClient.OnDisconnect -= OnSocketDisconnected;
        }
    }

    public void RequestUser(string name, string pwd, Action<int> callback)
    {
        string sign = Util.MD5Encrypt($"{name}{pwd}{this.sign}");

        NetworkManager.Instance.SendGetHttp(
            $"{AppConst.LoginRoot_Url}tk/userLogin?userName={name}&password={pwd}&sign={sign}",
            (str) =>
            {
                Debug.Log("userLogin");
                Debug.Log(str);
                if (str == null) return;
                    
                JObject data = JObject.Parse(str);

                if ((int)data["code"] == 0)
                {
                    openId = data["parms"]["openId"].ToString();
                    token = data["parms"]["token"].ToString();
                }
                callback?.Invoke((int)data["code"]);
            });
        
    }

    public void RequestRegist(string name, string pwd, Action callback)
    {
        string sign = Util.MD5Encrypt($"{name}{pwd}{this.sign}");

        NetworkManager.Instance.SendGetHttp(
            $"{AppConst.LoginRoot_Url}tk/registerUser?userName={name}&password={pwd}&repeat={pwd}&sign={sign}",
            (str) =>
            {
                Debug.Log("RequestRegist");
                Debug.Log(str);
                if (str == null) return;
                    
                JObject data = JObject.Parse(str);
                callback?.Invoke();
            });
    }
}

// 登录响应数据结构
[Serializable]
public class LoginResponseHttp
{
    public bool success;
    public int userId;
    public string token;
    public string errorMessage;
}